package com.ruoyi.function.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.function.domain.InterchangeStat;
import com.ruoyi.function.service.IInterchangeStatService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 枢纽互通统计Controller
 * 
 * @author ruoyi
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/function/InterchangeStat")
public class InterchangeStatController extends BaseController
{
    @Autowired
    private IInterchangeStatService interchangeStatService;

    /**
     * 查询枢纽互通统计列表
     */
    @PreAuthorize("@ss.hasPermi('function:InterchangeStat:list')")
    @GetMapping("/list")
    public AjaxResult list(InterchangeStat interchangeStat)
    {
        List<InterchangeStat> list = interchangeStatService.selectInterchangeStatList(interchangeStat);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = interchangeStat.getRoadName() != null && !interchangeStat.getRoadName().isEmpty() ||
                                   interchangeStat.getNodeName() != null && !interchangeStat.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<InterchangeStat> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出枢纽互通统计列表
     */
    @PreAuthorize("@ss.hasPermi('function:InterchangeStat:export')")
    @Log(title = "枢纽互通统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InterchangeStat interchangeStat)
    {
        List<InterchangeStat> list = interchangeStatService.selectInterchangeStatList(interchangeStat);
        // 构建树形结构
        List<InterchangeStat> treeList = buildTree(list);
        // 只导出第二层的数据，并将第一层的路段名称存入第二层的路段名称中
        List<InterchangeStat> exportList = new ArrayList<>();
        for (InterchangeStat parent : treeList) {
            if (parent.getChildren() != null && !parent.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<InterchangeStat> children = (List<InterchangeStat>) parent.getChildren();
                for (InterchangeStat child : children) {
                    // 创建新的对象避免修改原数据
                    InterchangeStat exportItem = new InterchangeStat();
                    // 复制子节点的所有属性
                    exportItem.setId(child.getId());
                    exportItem.setParentId(child.getParentId());
                    exportItem.setNodeName(child.getNodeName());
                    exportItem.setMainLength(child.getMainLength());
                    exportItem.setRampAvgLength(child.getRampAvgLength());
                    exportItem.setTollCenterLength(child.getTollCenterLength());
                    exportItem.setApproachAvgLength(child.getApproachAvgLength());
                    exportItem.setRemark(child.getRemark());
                    // 将第一层的路段名称存入第二层的路段名称中
                    exportItem.setRoadName(parent.getRoadName());
                    exportList.add(exportItem);
                }
            }
        }
        ExcelUtil<InterchangeStat> util = new ExcelUtil<InterchangeStat>(InterchangeStat.class);
        util.exportExcel(response, exportList, "枢纽互通统计数据");
    }

    /**
     * 构建树形结构
     */
    private List<InterchangeStat> buildTree(List<InterchangeStat> list) {
        // 构建父子关系映射
        Map<Long, InterchangeStat> nodeMap = new HashMap<>();
        List<InterchangeStat> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (InterchangeStat node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (InterchangeStat node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                InterchangeStat parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<InterchangeStat>());
                    }
                    @SuppressWarnings("unchecked")
                    List<InterchangeStat> children = (List<InterchangeStat>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }

    /**
     * 获取枢纽互通统计详细信息
     */
    @PreAuthorize("@ss.hasPermi('function:InterchangeStat:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(interchangeStatService.selectInterchangeStatById(id));
    }

    /**
     * 新增枢纽互通统计
     */
    @PreAuthorize("@ss.hasPermi('function:InterchangeStat:add')")
    @Log(title = "枢纽互通统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InterchangeStat interchangeStat)
    {
        return toAjax(interchangeStatService.insertInterchangeStat(interchangeStat));
    }

    /**
     * 修改枢纽互通统计
     */
    @PreAuthorize("@ss.hasPermi('function:InterchangeStat:edit')")
    @Log(title = "枢纽互通统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InterchangeStat interchangeStat)
    {
        return toAjax(interchangeStatService.updateInterchangeStat(interchangeStat));
    }

    /**
     * 删除互通立交统计
     */
    @PreAuthorize("@ss.hasPermi('function:interchangeStat:remove')")
    @Log(title = "互通立交统计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            if (interchangeStatService.hasChildById(id)) {
                return AjaxResult.error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(interchangeStatService.deleteInterchangeStatByIds(ids));
    }
}
